'use strict';
/**
 * @class service.exchange
 * @this service.exchange
 * @classdesc 用户积分兑换服务
 * @type {*|exports|module.exports}
 */
var util = require('../util'),
    sandbox = util.sandbox,
  weixinDao = require('../db').weixinuser;
sandbox.on(sandbox.MSG.EXCH_POINT_TO_VPN_TIME, toVpnTime);

/**
 * 以天为单位兑换vpn时间;
 * 根据传入的天数计算需要扣除的point
 * point不足时, 取能兑换的最大天数
 * @param dates 需要兑换的天数
 */
function toVpnTime (msg) {

  if (msg && msg.openid && msg.dates && !isNaN(msg.dates)) {

    var fixedDates = msg.dates;
    // 取得point
    weixinDao.findByOpenId(msg.openid)
      .then(function (applicant) {
        if (applicant) {
          var R = util.config.exchange_rate.point_vpn_time;
          // 用户point能兑换的最大天数
          var maxDatesCouldExchangeFromPoint = util.getInteger(applicant.point * R),

              // 用户剩余vpn天数能用来兑换的部分(有可能是小数, 向下取整); 小于0按0处理
              maxDatesCouldExchangeToPoint   = util.getInteger(util.getInteger((applicant.due_date - Date.now()) / (1000 * 3600 * 24)) / R) * R;

          // 非整数修正(1.5 取 1; -1.5 取 -1; 0.5, -0.5 都取 0)
          fixedDates = util.getInteger(fixedDates / R) * R;

          // 退出计算的条件
          if (fixedDates == 0 ||
            fixedDates < 0 && maxDatesCouldExchangeToPoint < 0 ||
            fixedDates > 0 && maxDatesCouldExchangeFromPoint == 0) {
            return;
          }

          // 超过上下限时对fixedDates的修正
          if (maxDatesCouldExchangeFromPoint < fixedDates || fixedDates < -1 * maxDatesCouldExchangeToPoint) {
            fixedDates >= 0 ? fixedDates = maxDatesCouldExchangeFromPoint : fixedDates = -1 * maxDatesCouldExchangeToPoint;
          }

          applicant.point    = applicant.point - fixedDates / R;
          applicant.due_date = applicant.due_date + (fixedDates * 1000 * 3600 * 24);
          return applicant.save()
            .then(sandbox.emit.bind(sandbox, sandbox.MSG.LOG_POINTHISTORY, {
              triggered_by     : applicant.openid,
              triggered_by_name: applicant.nickname,
              awarded_to       : '',
              awarded_to_name  : '',
              create_time      : Date.now(),
              action_type      : 'exchange',
              point            : fixedDates / R * -1,
              exchange         : {
                exchange_type: sandbox.MSG.EXCH_POINT_TO_VPN_TIME,
                amount       : fixedDates
              }
            }));
        }
      }).catch(util.log.log2Error);
  }
}